<template>
    <view class="page-register-index">
        <view class="mx-4">
            <u-form ref="form1" label-width="160rpx">
                <u-form-item label="手机号">
                    <u-input v-model="form.phone" placeholder="请选择" />
                </u-form-item>
                <u-form-item label="验证码" borderBottom>
                    <view class="flex">
                        <u-input
                            class="flex-1"
                            v-model="form.code"
                            placeholder="请输入验证码"
                            :border="false"
                        />
                        <view @click="sendSms">
                            <u-verification-code
                                ref="uCodeRef"
                                :seconds="60"
                                @change="codeChange"
                                change-text="x秒"
                            />
                            {{ codeTips }}
                        </view>
                    </view>
                </u-form-item>
            </u-form>
            <view class="mt-[40rpx]">
                <u-button class="btn-cyan-gradient" shape="circle" :loading="btnLoading" @click="submitForm"> 登录 </u-button>
            </view>
        </view>
    </view>
</template>
<script setup lang="ts">
const {proxy} = getCurrentInstance() as ComponentInternalInstance;
import { useAppStore } from '@/stores/app'
let appStore = useAppStore();
const uCodeRef = shallowRef()
const codeTips = ref('')
const form = reactive({
    phone: '',
    code: '',
});
let btnLoading = ref(false);
const codeChange = (text: string) => {
    codeTips.value = text
};
const sendSms = () => {
    if(!proxy.$verify.mobile(form.phone)){
        return false;
    }
    if (uCodeRef.value?.canGetCode) {
        proxy.$http('get', '/app/appmobile/'+ form.phone, {}, (data,msg) => {
            uni.$u.toast('发送成功')
            uCodeRef.value?.start()
        });
    }
};
const verifyForm = () => {
    if(!proxy.$verify.mobile(form.phone)){
        return false;
    }
    if(!proxy.$verify.null(form.code, '请输入验证码')){
        return false;
    }
    return true;
};
const submitForm = () => {
    if(!verifyForm()){
        return;
    }
    appStore.phoneLogin(form).then(res => {
        let url = uni.getStorageSync('beforeLogin');
        if(url){
            proxy.$util.gotoPage(url)
        }else{
            uni.switchTab({
                url: '/pages/home/index'
            })
        }
    });
};
</script>
<style>
page{height:100%;}
</style>